package com.way.fileexplorer.adapters;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import com.way.fileexplorer.R;
import com.way.fileexplorer.fragments.BaseFragment;
import com.way.fileexplorer.util.FileType;
import com.way.fileexplorer.util.FileUtil;
import com.way.fileexplorer.util.ImageLoader;
import com.way.fileexplorer.util.IntentUtil;
import com.way.fileexplorer.util.NotifyManager;
import com.way.fileexplorer.util.Slog;

public class FileListAdapter extends FileAdapter {
    private BaseFragment mAttachedFragment;
    private File mCurrentPath;
    private File mTopPath;
    private Context mContext;
    private ImageLoader imageLoader;
    private ListView mListView;
    // Bug 201542 Begin
    private int mCurrentFileIndex = 0;
    private File[] mFiles = null;
    private static final int MAX_LOAD_ITEM_COUNT = 50;
    // Bug 201542 End
    
    protected FileListAdapter(Context context, ListView list) {
        super(context);
        mContext = context;
        imageLoader = new ImageLoader(mContext);
        mListView = list;
    }

    public static FileListAdapter getFileListAdapter(Context context, ListView list) {
        if (context == null) {
            throw new NullPointerException();
        }
        FileListAdapter adapter = new FileListAdapter(context, list);
        return adapter;
    }

    public void stopObserver() {

    }
// useless now 
//    public void restoreObeserver() {
//        if (mCurrentPath != null && mCurrentPath.exists()) {
//            mObeserver.startWatching();
//        }
//    }

    public FileListAdapter attachFragment(BaseFragment fragment) {
        mAttachedFragment = fragment;
        return this;
    }

    // TODO: In future version, users can set their top path.
    public FileListAdapter initWithPath(File topPath) {
        if (topPath == null) {
            throw new NullPointerException();
        }
        mTopPath = topPath;
        mCurrentPath = topPath;
        mTopString = mTopPath.getAbsolutePath();
        mCurrentString = mCurrentPath.getAbsolutePath();
        refresh();
        return this;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        ViewHolder vHolder = (ViewHolder) view.getTag(R.id.action_paste_mode_cancel);
        view.setTag(position);
        File file = mFileList.get(position);
        if (file.isDirectory()) {
            vHolder.fileIcon.setImageResource(R.drawable.file_item_folder_ic);
        } else {
            int fileType = FileType.getFileType(mContext).getFileType(file);
            view.setTag(R.id.viewtag_filetype, fileType);
            vHolder.fileIcon.setImageResource(fileType);
            if(fileType == FileType.FILE_TYPE_IMAGE){
                imageLoader.loadImage(position, file.getPath(), imageLoadListener, true);
            }
        }
        return view;
    }
    ImageLoader.OnImageLoadListener imageLoadListener = new ImageLoader.OnImageLoadListener() {
        @Override
        public void onImageLoad(int position, Bitmap drawable) {
            View view = null;
            if(mListView != null){
                view = mListView.findViewWithTag(position);
            }
            if (view != null) {
                ImageView iv = (ImageView) view.findViewById(R.id.file_icon);
                iv.setImageBitmap(drawable);
            }
        }

    };

    public void execute(int position) {
        Slog.d("execute=" + position);
        File newPath = FileUtil.execute(mCurrentPath, mFileList.get(position), mContext);
        if (!newPath.equals(mCurrentPath)) {
            mCurrentPath = newPath;
            refresh();
        }else{
            int fileType = FileType.getFileType(mContext).getFileType(mFileList.get(position));
            Intent intent = IntentUtil.getIntentByFileType(mContext, fileType, mFileList.get(position));
            Log.i(TAG,"file type = " + fileType );
            Log.i(TAG,"intent = " + intent);
            if(intent != null) {
                mContext.startActivity(intent);
            } else {
                NotifyManager.getInstance(mContext).showToast(mContext.getResources().getString(R.string.msg_invalid_intent));
            }
        }
    }

    public void refresh() {
        Slog.d("refreshing" + "mCurrentPath = " + mCurrentPath.getPath());
        mFileList.clear();

        // bug 211092 begin
        // stop old imageLoader, create an new imageLoader
        if (imageLoader != null) {
            imageLoader.stop();
            imageLoader = new ImageLoader(mContext);
        }
        // bug 211092 end

        // Bug 201542 Begin
        File[] files = mFiles = mCurrentPath.listFiles();
        if (files == null) {
            return;
        }
        int add_count = 0;
        mCurrentFileIndex = 0;
        // Bug 201542 End
        for (File f : files) {
            final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
            boolean display = settings.getBoolean("display_hide_file", false);
            Log.i(TAG,"display hidden file = " + display);
            // Bug 201542 Begin
            mCurrentFileIndex++;
            // Bug 201542 End
            if(f.isHidden()){
                Log.i(TAG,f + "is hidden");
                if(display){
                    if(f.exists()){
                        Log.i(TAG,"show " + f);
                        mFileList.add(f);
                        // Bug 201542 Begin
                        add_count++;
                        // Bug 201542 End
                    }
                }
            }else{
                if(f.exists()){
                    Log.i(TAG,"show " + f);
                    mFileList.add(f);
                    // Bug 201542 Begin
                    add_count++;
                    // Bug 201542 End
                }
            }
            // Bug 201542 Begin
            if (add_count >= MAX_LOAD_ITEM_COUNT) {
                break;
            }
            // Bug 201542 End
        }
     // Bug 201542 Begin
        if (mCurrentPath.equals(mTopPath)) {
            mCurrentString = mTopString;
        } else {
            mCurrentString = mCurrentPath.getAbsolutePath();
        }
        if (null != mAttachedFragment) {
            mAttachedFragment.onFolderChanged();
        }
        startSort();
        notifyDataSetChanged();

    }

    /**
     * Go up level.
     * 
     * @return Return if finish activity.
     */
    public boolean popupFolder() {
        if (mCurrentPath == null) {
            Slog.d("currentpath == null");
	    return false;
        }
        if (mTopPath.getPath().equals(mCurrentPath.getPath())) {
            return true;
        }
        mCurrentPath = mCurrentPath.getParentFile();
        refresh();
        return false;
    }

    public File getCurrentPath() {
        return mCurrentPath;
    }
    public void setCurrentPath(File currentPath) {
        mCurrentPath = currentPath;
        refresh();
    }

    public File getTopPath() {
        return mTopPath;
    }
    // Bug 201542 Begin
    public void loadMoreIfNecessary() {

        int count = mFiles.length;
        final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
        boolean display = settings.getBoolean("display_hide_file", false);
        Log.d(TAG, "loadMoreIfNessary Enter count = " + count
                + " display = " + display
                + "mCurrentFileIndex = " + mCurrentFileIndex);

        if (mCurrentFileIndex < count) {
            int i, j = 0;
            for (i = mCurrentFileIndex; i < count; i++) {

                if (j >= MAX_LOAD_ITEM_COUNT) {
                    break;
                }
                if (mFiles[i].isHidden()) {
                    Log.i("Minghui", mFiles[i] + "is hidden");
                    if (display) {
                        if (mFiles[i].exists()) {
                            Log.i("Minghui", "show " + mFiles[i]);
                            mFileList.add(mFiles[i]);
                            j++;
                        }
                    }
                } else {
                    if (mFiles[i].exists()) {
                        Log.i("Minghui", "show " + mFiles[i]);
                        mFileList.add(mFiles[i]);
                        j++;
                    }
                }
            }
            mCurrentFileIndex = i;
            if (null != mAttachedFragment) {
                mAttachedFragment.onFolderChanged();
            }
            startSort();
            notifyDataSetChanged();
        }

    }
    // Bug 201542 End
}
